<template>
	<view class="page">
		<!-- 顶部标题区 -->
		<view class="hero">
			<text class="hero-title">Exhibition ⛪</text>
			<view class="hero-add" @tap="onAddFootprint">+</view>
		</view>

		<!-- 展览记录 -->
		<view class="section">
			<text class="section-title">展览记录</text>
			<view class="empty" v-if="!isLoading && !records.length">暂无展览，点击右上角“+”新建</view>
			<view class="list" v-else-if="!isLoading">
				<view class="card" v-for="rec in records" :key="rec.recordId" @click="openDetail(rec)">
					<image class="card-cover" :src="rec.coverImageUrl || '/static/test.png'" mode="aspectFill" />
					<view class="card-title">{{ rec.title }}</view>
					<view class="card-sub">{{ rec.galleryName }}</view>
				</view>
			</view>
		</view>

		<!-- 自定义底部导航栏 -->
		<CustomTabBar :currentIndex="2" />
	</view>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import CustomTabBar from '@/components/CustomTabBar.vue';
import { getRecordList } from '@/services/api/backendApi'

const records = ref([])
const isLoading = ref(false)

async function loadRecords() {
  try {
    console.log('📥 [足迹] 开始加载展览记录列表')
    isLoading.value = true
    // 显示加载中弹窗
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    const res = await getRecordList(1, 50)
    console.log('✅ [足迹] 展览记录接口返回:', res)
    const data = res.data || res
    const list = data.records || []
    records.value = Array.isArray(list) ? list : []
    console.log('📦 [足迹] total:', data.total, 'records length:', records.value.length)
    console.log('📦 [足迹] 归一化后的记录数:', records.value.length)
    
    // 加载成功后显示提示
    uni.showToast({
      title: '加载成功',
      icon: 'success',
      duration: 1500
    })
  } catch (e) {
    console.error('❌ [足迹] 加载展览记录失败:', e)
    uni.showToast({
      title: '加载展览失败', 
      icon: 'none',
      duration: 2000
    })
  } finally {
    isLoading.value = false
    // 隐藏加载中弹窗
    uni.hideLoading()
  }
}

function handleExhibitionSaved(newRecord) {
  console.log('🆕 [足迹] 收到新建展览事件:', newRecord)
  if (!newRecord) return
  const record = {
    recordId: newRecord.recordId || newRecord.id,
    title: newRecord.title,
    galleryName: newRecord.museum || newRecord.galleryName,
    createdAt: newRecord.createdAt || new Date().toISOString(),
    coverImageUrl: newRecord.coverImageUrl || newRecord.coverImageUrl || newRecord.coverImage,
    imageCount: newRecord.imageCount || 0
  }
  // 去重：如已存在则更新并置顶
  const idx = records.value.findIndex(r => (r.recordId || r.id) === record.recordId)
  if (idx > -1) {
    const next = [...records.value]
    next.splice(idx, 1)
    records.value = [record, ...next]
  } else {
    records.value = [record, ...records.value]
  }
}

onMounted(() => {
  loadRecords()
  uni.$on('exhibitionSaved', handleExhibitionSaved)
})

onBeforeUnmount(() => {
  uni.$off('exhibitionSaved', handleExhibitionSaved)
})

// 添加足迹
function onAddFootprint() {
	uni.navigateTo({ url: '/pages/footprint/create' })
}

function openDetail(rec) {
  if (!rec || !rec.recordId) {
    uni.showToast({ title: '无效展览', icon: 'none' })
    return
  }
  console.log('🔎 [足迹] 打开展览详情:', rec)
  uni.navigateTo({ url: `/pages/footprint/detail?recordId=${rec.recordId}` })
}
</script>

<style>
.page {
	min-height: 100vh;
	background-color: #0c0c0c;
	padding: 16px 14px 24px 14px;
	position: relative;
}

.hero {
	position: relative;
	height: 80px;
	margin-top: 24px;
}

.hero-title {
	color: #ffffff;
	font-size: 44px;
	font-weight: 600;
	font-family: 'Fugaz One','Apple Color Emoji','Segoe UI Emoji','Noto Color Emoji',sans-serif;
}

.hero-add {
	position: absolute;
	right: 0;
	top: 10px;
	width: 32px;
	height: 32px;
	border-radius: 16px;
	border: 1px solid #ffffff;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #ffffff;
}

.section {
	margin-top: 20px;
}

.section-title {
	color: #ffffff;
	font-size: 20px;
	font-weight: 500;
	margin-bottom: 10px;
}

.list {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 14px;
}

.card {
	background-color: transparent;
	border-radius: 10px;
	width: 168px;
	height: 230px;
	position: relative;
}

.card-cover {
	width: 168px;
	height: 190px;
	border-radius: 10px;
}

.card-title {
	margin-top: 6px;
	color: #ffffff;
	font-size: 14px;
	font-weight: 600;
}

.card-sub {
	color: #cccccc;
	font-size: 12px;
}
</style>